package com.softeem.sss.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtils {

	public static final String DRIVER = "com.mysql.jdbc.Driver";
	public static final String URL = "jdbc:mysql://127.0.0.1:3306/sss";
	public static final String USERNAME = "root";
	public static final String PASSWORD = "root";

	
	static{
		try {
			//加载驱动
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 封装连接获取
	 * @return
	 */
	public static Connection getConn(){
		try {
			return DriverManager.getConnection(URL, USERNAME, PASSWORD);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 关闭资源
	 * @param rs
	 * @param ps
	 * @param conn
	 */
	public static void close(ResultSet rs,PreparedStatement ps,Connection conn){
			try {
				if(rs != null)rs.close();
				if(ps != null)ps.close();
				if(conn != null)conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
	}
	
	/**
	 * 封装通用增删改操作(更新)
	 * @param sql	需要被执行的sql语句
	 * @param prams  执行sql语句时需要传入的参数
	 * @return  执行结果
	 */
	public static boolean exeUpdate(String sql,Object... params){
		Connection conn = getConn();
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			for(int i = 0;i < params.length;i++){
				ps.setObject(i + 1, params[i]);
			}
			return ps.executeUpdate() > 0 ? true : false;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			close(null, ps, conn);
		}
		return false;
	}
	
	/**
	 * 封装通用查询操作（可以对任意表，任意查询条件进行查询）
	 * @param sql
	 * @param params
	 * @return
	 */
	public static ResultSet exeQuery(String sql,Object... params){
		Connection conn = getConn();
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			for(int i = 0;i < params.length;i++){
				ps.setObject(i + 1, params[i]);
			}
			return ps.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) {
		System.out.println(getConn());
	}
}
